import React, { Suspense } from 'react';
import { useRoutes, useNavigate, Navigate } from 'react-router-dom';
import routes, { routeType } from './routes';
import { Spin } from 'antd';
import lodash_map from 'lodash/map';

export default function Routes() {
  let element = useRoutes(renderRoutes(routes));
  return element;
}

const renderRoutes = (routes: Array<routeType>) => {
  return lodash_map(routes, (item: routeType) => {
    interface resType extends routeType {
      element?: any;
    }
    let res: resType = { ...item };
    // if (!item?.path) return res;
    //component?
    if (item?.component) {
      const Component = React.lazy(item.component);
      res.element = (
        <Suspense fallback={<Spin size="large" />}>
          <BeforeEach route={item}>
            <Component />
          </BeforeEach>
        </Suspense>
      );
    }
    //children ?
    if (item?.children) {
      res.children = renderRoutes(item.children);
    }
    //redirect重定向
    if (item?.redirect) {
      res.element = <Navigate to={item.redirect} replace></Navigate>;
    }
    return res;
  });
};

function BeforeEach(props: { route: routeType; children: any }) {
  if (props?.route?.meta?.title) {
    document.title = props.route.meta.title;
  }
  if (props?.route?.meta?.needLogin) {
    //是否登录??
    const navigate = useNavigate();
    navigate('/Login');
  }
  return <div>{props.children}</div>;
}
